package cn.gok.front.service.impl;

import cn.gok.front.config.PasswordTokenCache;
import cn.gok.front.dao.UserDAO;
import cn.gok.front.service.IUserService;
import cn.gok.gok_mall.entity.User;
import cn.gok.gok_mall.responseData.ResultData;
import cn.hutool.crypto.digest.DigestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @Author: chenfan
 * @Description:
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    UserDAO userDAO;

    @Override
    public ResultData queryUserByUserNameAndPassword(String userName, String password) {

        //对用户提交的密码进行一次加密操作
        String  encryptionPassword = DigestUtil.md5Hex(password);

        User user = userDAO.queryUserByUserNameAndPassword(userName,encryptionPassword);
        if (user == null){
            return ResultData.fail("用户或密码错误");
        }
        return ResultData.createData(user);
    }

    @Override
    public ResultData queryUserPasswordQuestion(String userName) {
        String question = userDAO.queryUserPasswordQuestion(userName);
        if (question != null){
           return ResultData.createData(question);
        }

        return ResultData.fail("该用户未设置找回密码问题");
    }

    @Override
    public ResultData checkUserPasswordAnswer(String username, String question, String answer) {
        int i = userDAO.checkUserPasswordAnswer(username, question, answer);
        if (i <= 0){
            return ResultData.fail("问题输入不正确，验证失败请重试");
        }

        //如果验证成功，先生成一个token凭证
        String token = UUID.randomUUID().toString();

        //需要将token放入本地服务器缓存
        PasswordTokenCache.putToken(username,token);

        //将token凭证发送给前端
        return ResultData.createData(token);
    }
}
